﻿#region - 版 本 注 释 -
/*----------------------------------------------------------------
 * 版权所有 (c) 2024   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-GLJ2Q8J
 * 公司名称：
 * 命名空间：AutoCAD.EntityTool
 * 唯一标识：3b617350-31ef-4d14-b07c-78290c7493b3
 * 文件名：EntityTools
 * 当前用户域：DESKTOP-GLJ2Q8J
 * 
 * 创建者：Guo-79991
 * 电子邮箱：799919859@qq.com
 * 创建时间：2024/7/15 11:53:52
 * 版本：V1.0.0
 *
 * 功能描述(Description):
 * 参考文档(Reference):
 * 数据表(Tables):
 * 作者(Author):Guo
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion - 版 本 注 释 -



namespace AutoCAD.EntityTools
{
    /// <summary>
    /// CAD文件操作工具类
    /// </summary>
    public static class CadFileOperationTools
    {
        /// <summary>
        /// 保存当前图形
        /// </summary>
        public static void SaveCurrentDrawing(this Document doc)
        {
            try
            {
                //Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;

                if (string.IsNullOrEmpty(db.Filename))
                {
                    // 如果文件未保存过，调用另存为
                    SaveDrawingAs(doc);
                }
                else
                {
                    using (DocumentLock docLock = doc.LockDocument())
                    {
                        db.SaveAs(db.Filename, DwgVersion.Current);
                        doc.Editor.WriteMessage("\n图形已保存: " + db.Filename);
                    }
                }
            }
            catch (Exception ex)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"\n保存错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 另存当前图形
        /// </summary>
        public static void SaveDrawingAs(this Document doc)
        {
            try
            {
                //Document doc = Application.DocumentManager.MdiActiveDocument;
                Editor ed = doc.Editor;

                PromptSaveFileOptions saveOpts = new PromptSaveFileOptions("\n选择保存位置");
                saveOpts.Filter = "AutoCAD图形 (*.dwg)|*.dwg";
                saveOpts.InitialDirectory = Path.GetDirectoryName(doc.Name);
                saveOpts.DialogName = string.IsNullOrEmpty(doc.Name) ? "Drawing1.dwg" : Path.GetFileName(doc.Name);

                PromptFileNameResult saveResult = ed.GetFileNameForSave(saveOpts);

                if (saveResult.Status == PromptStatus.OK)
                {
                    using (DocumentLock docLock = doc.LockDocument())
                    {
                        doc.Database.SaveAs(saveResult.StringResult, DwgVersion.Current);
                        ed.WriteMessage("\n图形已另存为: " + saveResult.StringResult);
                    }
                }
            }
            catch (Exception ex)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"\n另存为错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 导出选定对象到新文件
        /// </summary>
        /// <param name="objectIds">要导出的对象ID列表</param>
        /// <param name="filePath">目标文件路径</param>
        public static void ExportObjectsToFile(this List<ObjectId> objectIds, string filePath)
        {
            if (objectIds == null || objectIds.Count == 0)
            {
                throw new ArgumentException("对象ID列表不能为空");
            }

            try
            {
                Database sourceDb = objectIds[0].Database;

                using (Database targetDb = new Database(true, true))
                {
                    ObjectIdCollection idCollection = new ObjectIdCollection(objectIds.ToArray());
                    sourceDb.Wblock(targetDb, idCollection, Point3d.Origin, DuplicateRecordCloning.Ignore);
                    targetDb.SaveAs(filePath, DwgVersion.Current);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"导出对象到文件失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 导出选定对象到新文件(带交互选择)
        /// </summary>
        public static void ExportSelectedObjects(this Document doc)
        {
            try
            {
                Editor ed = doc.Editor;

                // 选择对象
                PromptSelectionResult selResult = ed.GetSelection();
                if (selResult.Status != PromptStatus.OK) return;

                // 选择保存位置
                PromptSaveFileOptions saveOpts = new PromptSaveFileOptions("\n选择导出位置");
                saveOpts.Filter = "AutoCAD图形 (*.dwg)|*.dwg";
                saveOpts.InitialDirectory = Path.GetDirectoryName(doc.Name);
                saveOpts.DialogName = "Export.dwg";

                PromptFileNameResult saveResult = ed.GetFileNameForSave(saveOpts);
                if (saveResult.Status != PromptStatus.OK) return;

                // 执行导出
                ExportObjectsToFile(new List<ObjectId>(selResult.Value.GetObjectIds()), saveResult.StringResult);
                ed.WriteMessage($"\n已成功导出选定对象到: {saveResult.StringResult}");
            }
            catch (Exception ex)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"\n导出错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建新图纸
        /// </summary>
        public static void CreateNewDrawing(this Document doc)
        {
            try
            {
                //Document doc = Application.DocumentManager.MdiActiveDocument;
                doc.SendStringToExecute("NEW ", true, false, false);
            }
            catch (Exception ex)
            {
                doc.Editor.WriteMessage($"\n创建新图纸错误: {ex.Message}");
            }
        }


        /*使用示例
         * 
         * // 保存当前图纸
            CadFileOperations.SaveCurrentDrawing();

            // 另存当前图纸
            CadFileOperations.SaveDrawingAs();

            // 导出选定对象
            List<ObjectId> selectedIds = new List<ObjectId>(); // 获取选中的对象ID
            CadFileOperations.ExportObjectsToFile(selectedIds, "C:\\导出文件.dwg");

            // 交互式导出
            CadFileOperations.ExportSelectedObjects();

            // 创建新图纸
            CadFileOperations.CreateNewDrawing();
         */
    }
}
